package com.gerenboke.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gerenboke.domain.ResponseResult;
import com.gerenboke.domain.dto.UserDto;
import com.gerenboke.domain.dto.UserSaveDto;
import com.gerenboke.domain.entity.Role;
import com.gerenboke.domain.entity.User;
import com.gerenboke.domain.vo.PageVo;
import com.gerenboke.domain.vo.UserInfoVo;
import com.gerenboke.domain.vo.UserRoleVo;
import com.gerenboke.domain.vo.UserVo;
import com.gerenboke.enums.AppHttpCodeEnum;
import com.gerenboke.exception.SystemException;
import com.gerenboke.mapper.RoleMapper;
import com.gerenboke.mapper.UserMapper;
import com.gerenboke.service.RoleService;
import com.gerenboke.service.UserService;
import com.gerenboke.utils.BeanCopyUtils;
import com.gerenboke.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2022-11-14 22:47:37
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RoleService roleService;

    @Override
    public ResponseResult userInfo() {
        //获取当前用户id
        Long userId = SecurityUtils.getUserId();
        //根据用户id查询用户信息
        User user = getById(userId);
        //封装成UserInfoVo
        UserInfoVo vo = BeanCopyUtils.copyBean(user,UserInfoVo.class);
        return ResponseResult.okResult(vo);
    }

    @Override
    public ResponseResult updateUserInfo(User user) {
        updateById(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult register(User user) {
        //对数据进行非空判断
        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        //对数据进行是否存在的判断
        if(userNameExist(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if(nickNameExist(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }
        //...
        //对密码进行加密
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        //存入数据库
        save(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult userList(Long pageNum, Long pageSize, String userName, String phonenumber, String status) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Objects.nonNull(userName),User::getUserName,userName);
        queryWrapper.eq(Objects.nonNull(phonenumber),User::getPhonenumber,phonenumber);
        queryWrapper.eq(Objects.nonNull(status),User::getStatus,status);
        Page<User> page = new Page<>(pageNum,pageSize);
        page(page,queryWrapper);
        return ResponseResult.okResult(new PageVo(page.getRecords(),page.getTotal()));
    }

    @Override
    @Transactional
    public ResponseResult saveUser(UserSaveDto userSaveDto) {
        if (Objects.isNull(userSaveDto.getUserName())) {
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,userSaveDto.getUserName());
        Long count = getBaseMapper().selectCount(queryWrapper);
        if (count>0){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPhonenumber,userSaveDto.getPhonenumber());
        Long count1 = getBaseMapper().selectCount(lambdaQueryWrapper);
        if (count1>0){
            throw new SystemException(AppHttpCodeEnum.PHONENUMBER_EXIST);
        }
        LambdaQueryWrapper<User> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(User::getEmail,userSaveDto.getEmail());
        Long count2 = getBaseMapper().selectCount(lambdaQueryWrapper1);
        if (count2>0){
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }
        User user = BeanCopyUtils.copyBean(userSaveDto, User.class);
        //对密码进行加密
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        save(user);
        userSaveDto.getRoleIds().stream().map(roleId -> getBaseMapper().saveUserRole(user.getId(),Long.valueOf(roleId))).count();
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult deleteUser(Long id) {
        Long userId = SecurityUtils.getUserId();
        if (userId.equals(id)){
            throw new SystemException(AppHttpCodeEnum.DELETE_USER_ERROR);
        }
        boolean b = removeById(id);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult selectUser(Long id) {
        User user = getById(id);
        UserVo userVo = BeanCopyUtils.copyBean(user, UserVo.class);
        List<String> roleIds = getBaseMapper().selectroleIds(id);
        List<Role> roleList = roleService.list();
        return ResponseResult.okResult(new UserRoleVo(roleIds,roleList,userVo));
    }

    @Override
    @Transactional
    public ResponseResult updateUser(UserDto userDto) {
        User user = BeanCopyUtils.copyBean(userDto, User.class);
        updateById(user);
        getBaseMapper().deleteUserRole(user.getId());
        userDto.getRoleIds().stream().map(roleId -> getBaseMapper().saveUserRole(user.getId(),Long.valueOf(roleId))).count();
        return ResponseResult.okResult();
    }

    private boolean nickNameExist(String nickName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getNickName,nickName);
        return count(queryWrapper) > 0;
    }

    private boolean userNameExist(String userName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,userName);
        return count(queryWrapper) > 0;
    }
}

